<?php
class LoginApp extends CommonApp {

    //登录界面
    public function indexAct(){
      //用户已登陆直接跳转到通知页面
      if(My::user('member.memberid'))
        redirect(Router::encodeUrl('index.php?app=Index&act=index'));
      $this->display();
    }

    //注册界面
    public function registerAct(){
      //用户已登陆直接跳转到通知页面
      if(My::user('member.memberid'))
        redirect(Router::encodeUrl('index.php?app=Index&act=index'));
      $result = M('admin.category')->item2submenu('college',array('level'=>'1'));//学院
      $this->assign('result',$result);
      $this->display();
    }

    //注册界面
    public function reset_passwordAct(){
      //用户已登陆直接跳转到通知页面
      if(My::user('member.memberid'))
        redirect(Router::encodeUrl('index.php?app=Index&act=index'));
      $this->display();
    }


   	// //登录界面验证
    public function loginAct(){
    	if($_POST){
    		//用户名判断
    		if(empty($_POST['username']))
    			$this->ajaxReturn(300,'用户名不能为空！');
    		//密码判断
    		if(!My::is_string($_POST['password']))
    			$this->ajaxReturn(300,'密码不能为空！');
    		//判断验证码
    		$verify = new Verify();
        if(!$verify->check(My::arr2var($_POST,'verify')))
          $this->ajaxReturn(300,'验证码错误!');
        $result = DB('homeuser')->where("username='{$_POST['username']}' AND password='".md5(md5($_POST['password']))."'")->cache()->find();
        if(is_array($result)){
            $ok = self::doLogin($result['id'],'homeuser',$result);
            if($result)
                $this->ajaxReturn(200,'登陆成功!!');
            else
                $this->ajaxReturn(300,'登陆失败（设置登录状态时异常）');
        }else
            $this->ajaxReturn(300,'用户名或密码错误!');
    	}
    }

    //注册页面
    public function register_codeAct(){
    	if($_POST){
    		//用户名
    		if(!My::is_string($_POST['username'],array('c')))
    			$this->ajaxReturn(300,array('message'=>'真实姓名填写有误！','name'=>'username'));
        //院系
        if(empty($_POST['college']))
            $this->ajaxReturn(300,array('message'=>'请选择院系！','name'=>'college'));
            //专业
        if(empty($_POST['class']))
            $this->ajaxReturn(300,array('message'=>'请选择专业！','name'=>'class'));
        //邮箱名
        if(!My::is_email($_POST['email']))
          $this->ajaxReturn(300,array('message'=>'邮箱填写有误！','name'=>'email'));
        //手机号
        if(!My::is_tel($_POST['number']))
          $this->ajaxReturn(300,array('message'=>'手机号填写有误！','name'=>'number'));
    		//密码判断
    		if(!My::is_string($_POST['password']))
    			$this->ajaxReturn(300,array('message'=>'密码填写有误！','name'=>'password'));
    		//确认密码判断
    		if(!My::is_string($_POST['password2']))
    			$this->ajaxReturn(300,array('message'=>'确认密码填写有误！','name'=>'password2'));
    		if($_POST['password2'] !== $_POST['password'])
    			$this->ajaxReturn(300,array('message'=>'两次密码输入不一致！','name'=>'password2'));
    		//判断验证码
    		// $verify = new Verify();
      //   if(!$verify->check(My::arr2var($_POST,'verify')))
      //       $this->ajaxReturn(300,array('message'=>'验证码错误！','name'=>'verify'));
        // $result = DB('homeuser')->where("username='{$_POST['username']}'")->find();
        // if($result)
        //   $this->ajaxReturn(300,array('message'=>'该姓名已存在，请重新填写！','name'=>'username')); 
        $found = DB('homeuser')->where("number='{$_POST['number']}'")->find();
        if($found)
          $this->ajaxReturn(300,array('message'=>'该手机号已注册，请重新填写！','name'=>'number')); 
        $_POST['complete'] = '1';//信息完整度
        $_POST['password'] = md5(md5($_POST['password']));
        $_POST['adddate'] = date("Y-m-d H:i:s");
        $ok = DB('homeuser')->clear()->add($_POST);
  			if($ok>=0)	$this->ajaxReturn(200,"注册成功");
  			else		$this->ajaxReturn(300,"注册失败");
    	}
    }

    //修改密码
    public function resetAct(){
      if($_POST){
        //用户名
        if(!My::is_string($_POST['username'],array('c')))
          $this->ajaxReturn(300,array('message'=>'真实姓名填写有误！','name'=>'username'));
        //手机号
        if(!My::is_tel($_POST['number']))
          $this->ajaxReturn(300,array('message'=>'手机号填写有误！','name'=>'number'));
        //密码判断
        if(!My::is_string($_POST['password']))
          $this->ajaxReturn(300,array('message'=>'密码填写有误！','name'=>'password'));
        //确认密码判断
        if(!My::is_string($_POST['password2']))
          $this->ajaxReturn(300,array('message'=>'确认密码填写有误！','name'=>'password2'));
        if($_POST['password2'] !== $_POST['password'])
          $this->ajaxReturn(300,array('message'=>'两次密码输入不一致！','name'=>'password2'));
        //判断验证码
        // $verify = new Verify();
      //   if(!$verify->check(My::arr2var($_POST,'verify')))
      //       $this->ajaxReturn(300,array('message'=>'验证码错误！','name'=>'verify'));
        // $result = DB('homeuser')->where("username='{$_POST['username']}'")->find();
        // if($result==null)
        //   $this->ajaxReturn(300,array('message'=>'该姓名不存在，请重新填写！','name'=>'username')); 
        $found = DB('homeuser')->where("number='{$_POST['number']}'")->find();
        if($found==null)
          $this->ajaxReturn(300,array('message'=>'该手机号没有注册，请重新填写！','name'=>'number'));
        // $_POST['complete'] = '1';//信息完整度
        $_POST['password'] = md5(md5($_POST['password']));
        // $_POST['adddate'] = date("Y-m-d H:i:s");
        $ok = DB('homeuser')->where("number='{$_POST['number']}'")->save($_POST);
        if($ok>=0)  $this->ajaxReturn(200,"密码重置成功");
        else    $this->ajaxReturn(300,"密码重置失败");
      }
    }

    //注册页面及短信服务
    public function smsAct(){
      if($_POST){
            if(!$_POST['number'])
                $this->ajaxReturn(300,'手机号码没有填写!');
            if(!My::is_tel($_POST['number']))
                $this->ajaxReturn(300,'手机号码填写错误!');
            $Sendsms = new Sendsms();
            // $result = $Sendsms->sms($_POST['number']);
            $result['result'] = 'OK';
            $result['code'] = '222222';
            if($result['result'] == 'OK') $this->ajaxReturn(200,$result['code']);
        }else $this->display();
    }

  	/**
     * 设置登录状态数据操作
     * @param int $memberid 用户id
     * @param string $login_type 问卷类型
     */
    private function doLogin($memberid, $login_type,$result){  //在登录时已经查询数据库$result所有的数据，原本的id值作为memberid，数据库名为login_type的值
        if(!My::is_id($memberid)) return false;
        //当前登录用户的信息
        //$result = DB($login_type)->field('password',true)->where('id='.$memberid)->find();
        //if(!is_array($result)) return false;
        //更新当前登录IP/登录时间/登出时间
        DB($login_type)->field('login_ip')->where("id={$memberid}")->save(array('login_ip'=>get_client_ip()));
        //登录次数++
        //DB($login_type)->where('id='.$memberid)->setInc('hit');
        // $result['params'] = My::decodeJson($result['params']);
        $result['memberid'] = $memberid;
        //已有memberid，此处去除id
        unset($result['id']);  //因为之前的$result值包含所有的数据，因为要设定session值，去除id和password
        unset($result['password']);
        //设置前台用户登录session数据
        $_SESSION['member'] = $result;
        return true;
    }

    //联动
    public function getclassAct(){
        $option = "<option value='' selecct='selected'>请选择专业...</option>";
        if(!empty($_GET['id'])){
            $result = M('admin.category')->id2submenu($_GET['id']);//专业
            foreach($result as $value)
              $option .= "<option value=".$value['id'].">".$value['title']."</option>";  //這裡的.=是把右邊的字串加到左邊，就是要讓它連成多个<option>
            $this->ajaxReturn(200,$option);
        }else $this->ajaxReturn(200,$option);
    }

    /**
   	* 用户退出
   	*/
    public function logoutAct(){
      $this->checkLogin();
      $memberid = My::arr2var($_SESSION,'member.memberid');
      DB('homeuser')->field('loginout_time')->where("id={$memberid}")->save(array('loginout_time'=>date('Y-m-d H:i:s')));
      //删除本系统的session
      $_SESSION['member'] = '';
      rm_dir(DATA_DIR.'Cache');//cache缓存
      redirect(Router::encodeUrl('index.php?app=Login&act=index'));
    }

    //清除缓存
    function clear(){
      rm_dir(DATA_DIR.'Cache');//cache缓存
      rm_dir(DATA_DIR.'Field');//数据库模型缓存
      //rm_dir(DATA_DIR.'Log');//日志缓存
      //rm_dir(DATA_DIR.'Session');//Session文件
      $this->ajaxReturn(200, '已清空所有缓存文件！');
    }
}